
import http from 'wechat-http'
http.baseURL = 'https://live-api.itheima.net'

// 请求拦截
http.intercept.request = function (options) {
  // 添加请求头信息
  const defaultHeader = {}
  defaultHeader.Authorization = `Bearer ${getApp().token}`
  options.header = Object.assign({}, defaultHeader, options.header)
  return options

}

// 响应拦截
http.intercept.response = async function ({ data, config }) {
  if (data.code === 401) {
    // token失效
    if (config.url.includes('/refreshToken')) {
      // token refreshToken都失效,跳转登录页
      // 获取页面参数
      const pageInfo = getCurrentPages()
      const currPageInfo = pageInfo.pop()
      const redirectUrl = currPageInfo.route
      const isTabbar = wx.utils.isTabbar(redirectUrl)
      const routeType = isTabbar? 'switchTab' : 'redirectTo'


      return wx.redirectTo({
        url: `/pages/login/index?redirectUrl=/${redirectUrl}&routeType=${routeType}`,
      })
    }

    const app = getApp()
    const res = await http({
      url: '/refreshToken',
      method: 'post',
      header: {
        Authorization: 'Bearer ' + app.refreshToken
      }
    })
    // 存储token
    app.setToken('token', res.data.token)
    app.setToken('refreshToken', res.data.refreshToken)
    // 无感刷新token
    config = Object.assign(config, {
      header: {
        Authorization: 'Bearer ' + res.data.token
      }
    })
    return http(config)
  }
  return data

}

export default http
wx.http = http